#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>

#include <iostream>
#include <stdio.h>
#include <stdlib.h>

#define SOCKET_ERROR -1
#define SD_SEND 1
#define INVALID_SOCKET -1

#ifndef INADDR_NONE
#define INADDR_NONE ((unsigned long) -1)
#endif

using namespace std;

int logSocket;
const int kBufferSize = 1024;
const int kReturnBufferSize = 100;

//Resolve hostname into a usable address

u_long ResolveAddress(const char *remoteHost){
	//Assuming IP address(x.x.x.x) was passed
	u_long address = inet_addr(remoteHost);
	
	//remoteHost was not a valid ip address, try DNS resolution
	if(address == INADDR_NONE){
		hostent* hostEntry = gethostbyname(remoteHost);
		if(hostEntry == 0){
			//Get LastErrorMessage("Error")
			return INADDR_NONE;
		}
		address = *((u_long*)hostEntry->h_addr);
			
	}
	
	return address;
	
}

int main(){
	
	u_long ResolveAddress(const char *remoteHost);
	string remoteHost = "127.0.0.1";
	u_short port = 35999;
	int mySocket;
	string message = "Hello World";
	
	//This address that we have specified in the string has to be converted to 32 bytes of address which is conpatible with C++
	u_long address = ResolveAddress(remoteHost.c_str());
	cout<<address<<endl;
	
	//Create a stream socket
	mySocket = socket(AF_INET, SOCK_STREAM, 0);
	
	if(mySocket != INVALID_SOCKET)
	{
		sockaddr_in sinRemote;
		sinRemote.sin_family = AF_INET;
		sinRemote.sin_addr.s_addr = address;
		sinRemote.sin_port = htons(port);
		
		if(connect(mySocket,(sockaddr*)&sinRemote, sizeof(sockaddr_in)) == SOCKET_ERROR)
		{
			cout<<"Error connecting to remote process \n";
		}else{
			cout<<"Valid Connection";
		}		
		
		
	}else{
		cout<<"Invalid Socket\n";
	}
	
	int sendValue = send(mySocket, message.c_str(), message.length(),0);
	cout<<"sv:"<<sendValue<<endl;
	
	if(sendValue == SOCKET_ERROR){
		cout<<"send did'nt work\n";
	}
	
	return 0;
	
} 
